package com.example.ad.sdk.domain.ad.repositories

import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Interceptor
import okhttp3.Response

/**
 * 动态 替换 host Url
 */
class AdHostUrlInterceptor : Interceptor{
    override fun intercept(chain: Interceptor.Chain): Response {
        //获取原始的originalRequest
        val originalRequest = chain.request()
        //获取originalRequest的创建者builder
        val builder = originalRequest.newBuilder()
        //获取当前的url
        val oldUrl = originalRequest.url.host
        val newUrl = AdRetrofitClient.dynamic
        if (newUrl.isNotEmpty() && oldUrl != newUrl){
            //地址改变
            val baseURL = newUrl.toHttpUrlOrNull()

            if (baseURL != null) {
                //重建新的HttpUrl，需要重新设置的url部分
                val newHttpUrl: HttpUrl = originalRequest.url.newBuilder()
                    .scheme(baseURL.scheme) //http协议如：http或者https
                    .host(baseURL.host) //主机地址
                    .port(baseURL.port) //端口
                    .build()
                //获取处理后的新newRequest
                return chain.proceed(builder.url(newHttpUrl).build())
            }
        }
        return chain.proceed(builder.build())
    }
}